package com.zhzh.sc.demo.juc.thread;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * CompletableFuture 基本用法
 *
 * @author: dasouche
 * @date: 2021-03-17 15:52
 **/
public class CompletableFutureDemo {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        CompletableFuture<Double> a = CompletableFuture.supplyAsync(() -> getA());
        CompletableFuture<Double> b = CompletableFuture.supplyAsync(() -> getB());
        CompletableFuture<Double> c = CompletableFuture.supplyAsync(() -> getC());

        CompletableFuture.allOf(a, b, c).join();
        try {
            System.out.println(a.get()+b.get()+c.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        CompletableFuture.supplyAsync(() -> getA()).thenApply(String::valueOf).thenApply(str -> "price " + str).thenAccept(System.out::print);

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("spendAll=" + (System.currentTimeMillis() - start));
    }

    private static Double getA() {
        delay();
        return 1.0;
    }

    private static Double getB() {
        delay();
        return 2.0;
    }

    private static Double getC() {
        delay();
        return 3.0;
    }

    private static void delay() {
        int i = new Random().nextInt(1000);
        try {
            Thread.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("delay = " + i);
    }
}
